'use strict';

var config = require('../conf/config');
var response = require('./response');
var remoteRequest = require('../components/util/remoteRequest');
var xss = require('../components/util/htmlXss');


// 登录拦截
exports.webLoginAuth = function(req, res, next){
	if (req.session.tokenValid) {
        req.params = xss(req.params);
        req.body = xss(req.body);
		next();
	} else {
		if (config.currEvn == 'test') {
            req.session.user = {id: 'zhangsan', userName:'张三', tenant: 'atwork', tokenValid : true};
			next();
		} else {
			response.error(res, config.errorCode.noLogin);
		}
	}
};

exports.adminLoginAuth = function(req, res, next){
    if (req.session.loginValid) {
        req.params = xss(req.params);
        req.body = xss(req.body);
        next();
    } else {
        if (config.currEvn == 'test') {
            req.session.user = config.users['admin']
            next();
        } else {
            response.error(res, config.errorCode.noLogin);
        }
    }
};

exports.logout = function(req, res){
	console.info('用户%s退出!', req.session.user);
	req.logout();
};

exports.adminLogin = function(req, res){
    var user = req.body.user;
    var pwd = req.body.pwd;
    console.info(req.body);
    var dbUser = config.users[user];

    if (dbUser && dbUser.pwd == pwd) {
        req.session.user = dbUser;
        req.session.user.loginValid = true;
        response.data(res, req.sessionID);
    } else {
        response.error(res, config.errorCode.loginAuthError);
    }
    
};

// 首次登录进行登录验证
exports.validUserToken = function(req, res){
    remoteRequest.validUserToken(req.body, function(isSucceed, data) {
        if (isSucceed) {
            req.session.user = req.body.user;
            req.session.user.tenant = 'atwork';
            req.session.user.tokenValid = true;
            response.data(res, req.sesionID);
        } else {
            response.error(res, config.errorCode.tokenAuthError);
        }
    });
};